import CommonModal from '@/views/ShoppingCart/components/CommonEditModal.tsx'
import { localShoppingData, tempData } from '@/views/ShoppingCart/LocalShoppingData.ts'
import { forwardRef, useCallback, useEffect, useRef, useState } from 'react'
import { Button, Checkbox, Input, Pagination, Upload, UploadProps } from 'antd'
import { getItem, initPageType, message, TOKEN, usePageChange } from '@hs-admin/utils'
import { RcFile } from 'antd/es/upload'
import { exportFileTemplate, exportWhiteCompanyFile, getCompanyList, postCompanyList } from '@/api/shoppingCart.ts'
import { commonInputProps } from '@/views/ShoppingCart/commonProps.ts'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10
}

const EditCompanyScope = forwardRef((props: { itemId: string; done: (() => void) | undefined; disabled?: boolean }, ref) => {
  const notEditable = !!props.disabled

  const haveCommon = !!localShoppingData('common')

  const [companyList, setCompanyList] = useState<
    Array<{
      name: string
      id: string
    }>
  >([])

  const [companyInfo, setCompanyInfo] = useState({
    id: '',
    count: 0
  })

  const tempSearchWord = useRef('')

  const [searchWord, setSearchWord] = useState('')

  const getList = useCallback(
    async (page: number, pageSize: number) => {
      if (!companyInfo.id) {
        throw 'no id'
      }
      const res = await getCompanyList(companyInfo.id, {
        page: page,
        page_size: pageSize,
        keywords: searchWord || undefined
      })
      setCompanyList(res.items)
      setCompanyInfo((prevState) => ({
        ...prevState,
        count: res.total
      }))
      return res.total as number
    },
    [companyInfo.id, searchWord]
  )

  const { pagination, resetPageAndTriggerRequest } = usePageChange(initPage, getList)

  const [uploading, setUploading] = useState(false)

  useEffect(() => {
    resetPageAndTriggerRequest()
  }, [companyInfo.id, searchWord])

  const uploadProps: UploadProps = {
    name: 'file',
    action: `${import.meta.env.VITE_DATA_SHOP_API_URL}/api/datashop/v3/company-id-spec-vals`,
    headers: {
      Authorization: `Bearer ${getItem(TOKEN)}`
    },
    beforeUpload(file) {
      const formData = new FormData()
      formData.append('file', file as RcFile)
      setUploading(true)
      postCompanyList(formData)
        .then((res) => {
          setCompanyInfo({
            id: res.id,
            count: 0
          })
          message.success('上传成功')
        })
        .finally(() => {
          setUploading(false)
        })

      return false
    }
  }

  const [useParent, setUseParent] = useState(false)

  useEffect(() => {
    let data = localShoppingData(props.itemId, 'companyInfo') ?? {
      id: '',
      count: 0
    }
    if (props.itemId !== 'common') {
      data = tempData('companyInfo') ?? {
        id: '',
        count: 0
      }
      const useP4 = tempData('p4') ?? false
      setUseParent(useP4)
    } else {
      setUseParent(false)
    }
    setCompanyInfo(data)
  }, [props.itemId])
  return (
    <CommonModal
      ref={ref}
      onOpen={() => {
        setCompanyList([])
        resetPageAndTriggerRequest()
      }}
      onOk={() => {
        if (notEditable) return
        props.done?.()
        if (props.itemId === 'common') {
          localShoppingData(props.itemId, { companyInfo })
        } else {
          tempData({ companyInfo })
          tempData({
            p4: useParent
          })
        }
      }}
      onCancel={() => {
        console.log('取消')
      }}
      title="企业白名单选择">
      <div>
        <h3 className="text-xl">白名单企业</h3>
        <div>
          {props.itemId !== 'common' && haveCommon && (
            <div>
              <Checkbox
                checked={useParent}
                onChange={(e) => {
                  setUseParent(e.target.checked)
                  if (e.target.checked) {
                    setCompanyInfo({
                      id: '',
                      count: 0
                    })
                  }
                }}>
                使用整体范围
              </Checkbox>
            </div>
          )}
        </div>
        {!useParent && (
          <>
            <div className="grid grid-cols-24 gap-4">
              <Input
                {...commonInputProps()}
                onChange={(e) => {
                  tempSearchWord.current = e.target.value
                }}
                className="col-span-12"
              />
              <Button
                type="primary"
                onClick={() => {
                  setSearchWord(tempSearchWord.current)
                }}
                className="col-span-3">
                搜索
              </Button>
            </div>
            <div className="flex justify-between py-4">
              <span>共计{companyInfo.count}条</span>
              <div className="flex gap-4">
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    if (companyInfo.id) {
                      exportWhiteCompanyFile(companyInfo.id)
                    } else {
                      exportFileTemplate()
                    }
                  }}>
                  导出企业
                </Button>
                {!notEditable && (
                  <Upload {...uploadProps} showUploadList={false}>
                    <Button type="primary" size="small" loading={uploading}>
                      上传企业
                    </Button>
                  </Upload>
                )}
              </div>
            </div>
            <div className="grid grid-cols-2 gap-2">
              <span className="text-xl">企业ID</span>
              <span className="text-xl">企业名称</span>
            </div>
            {companyList.map((item) => (
              <div key={item.id} className="grid grid-cols-2 gap-2">
                <span>{item.company_id}</span>
                <span>{item.company_name}</span>
              </div>
            ))}
            {companyInfo.count > 10 && <Pagination className="justify-end mt-4 flex" {...pagination} />}
          </>
        )}
      </div>
    </CommonModal>
  )
})

export default EditCompanyScope
